package cn.fenglaicaimi.util;

import cn.fenglaicaimi.base.domain.AccessTokenVo;
import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class AccessTokenUtil {
	private static AccessTokenVo accessTokenVo ;
	private static Properties p = new Properties();
	static{
		InputStream inStream = AccessTokenUtil.class.getClassLoader().getResourceAsStream("application.properties");
		try {
			p.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		refreshAccessToken();
	}
	
	private static void refreshAccessToken(){
		String appid = p.getProperty("wechat.appID");
		String appsecret = p.getProperty("wechat.appsecret");
		
		//获取access_token
		String accessTokenUrl = UrlUtil.ACCESS_TOKEN_URL+"?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
		String accessTokenRet = HttpUtil.get(accessTokenUrl);
		accessTokenVo = JSON.parseObject(accessTokenRet, AccessTokenVo.class);
		accessTokenVo.setCreateTime(new Date().getTime());
	}
	
	public static AccessTokenVo getAccessTokenVo(){
		if (!accessTokenVo.isVail()) {
			refreshAccessToken();
		}
		return accessTokenVo;
	}
	
	
	
}
